//
//  Congratulation.swift
//  Maze24
//
//  Created by Mars on 2020/12/21.
//

import SwiftUI
import AVFoundation

struct Congratulation: View {
  @Environment(\.presentationMode) var presentation
  @State var degree = 0.0
  @State var player: AVAudioPlayer!
  let clearnaceSound = URL(fileURLWithPath: Bundle.main.path(forResource: "success.wav", ofType: nil)!)
  
  var archievement = "unveil"
  var animation: Animation {
    Animation.easeInOut(duration: 0.5)
  }
  
  var currentDateTime: String {
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    
    return formatter.string(from: Date())
  }
  
  var body: some View {
    GeometryReader { proxy in
      HStack {
        Spacer()
        
        VStack(alignment: .center) {
          Spacer()
          
          Text("恭喜你，过关啦！")
            .font(.title)
            .fontWeight(.bold)
            
          Image(archievement)
            .resizable()
            .frame(width: proxy.size.width - 100, height: proxy.size.width - 100)
            .rotation3DEffect(
              .degrees(degree),
              axis: (x: 0.0, y: 1.0, z: 0.0))
            .animation(animation)
            .onAppear {
              degree = 360
            }
          
          Text("你于 \(currentDateTime) 获得了此成就")
            .font(.caption)
            .foregroundColor(.secondary)
            .padding(.horizontal, 50)
            .lineLimit(1)
          
          Spacer()
          
          Button("Bravo!") {
            player = try! AVAudioPlayer(contentsOf: clearnaceSound)
            player.play()
            degree += 360
          }
          .padding(.bottom, 25)
          
          Button("返回") {
            self.presentation.wrappedValue.dismiss()
          }
        }
        
        Spacer()
      }
      
    }
  }
}

struct Congratulation_Previews: PreviewProvider {
  static var previews: some View {
    return Congratulation(archievement: "smile9")
  }
}
